package com.example.receiptocr.home

import android.graphics.Color
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.example.receiptocr.viewModels.ExpenseChartState
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.ValueFormatter
import java.time.LocalDate
import java.time.format.DateTimeFormatter

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ExpenseChart(
    state: ExpenseChartState,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier
            .fillMaxWidth()
            .padding(bottom = 12.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Column(
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth()
        ) {
            when (state) {
                is ExpenseChartState.Loading -> {
                    CircularProgressIndicator(
                        modifier = Modifier.align(Alignment.CenterHorizontally)
                    )
                }
                is ExpenseChartState.Empty -> {
                    Text(
                        text = "暂无消费数据",
                        color = androidx.compose.ui.graphics.Color.Gray,
                        modifier = Modifier.padding(vertical = 16.dp)
                    )
                }
                is ExpenseChartState.Success -> {
                    AndroidView(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(250.dp), // 增加高度以适应标签
                        factory = { context ->
                            LineChart(context).apply {
                                description.isEnabled = false
                                legend.isEnabled = false
                                setTouchEnabled(true)
                                setScaleEnabled(false)
                                setPinchZoom(false)
                                
                                // 配置X轴
                                xAxis.apply {
                                    position = XAxis.XAxisPosition.BOTTOM
                                    setDrawGridLines(false)
                                    granularity = 1f
                                    labelRotationAngle = -45f // 旋转标签以防重叠
                                    setDrawLabels(true)
                                    textSize = 10f
                                    valueFormatter = object : ValueFormatter() {
                                        override fun getFormattedValue(value: Float): String {
                                            return state.expenses.getOrNull(value.toInt())?.let { data ->
                                                LocalDate.parse(data.date)
                                                    .format(DateTimeFormatter.ofPattern("MM-dd"))
                                            } ?: ""
                                        }
                                    }
                                }

                                // 配置左Y轴
                                axisLeft.apply {
                                    setDrawGridLines(true)
                                    textSize = 12f
                                    valueFormatter = object : ValueFormatter() {
                                        override fun getFormattedValue(value: Float): String {
                                            return "¥${value.toInt()}"
                                        }
                                    }
                                }
                                
                                // 禁用右Y轴
                                axisRight.isEnabled = false

                                // 设置额外的底部边距以显示日期标签
                                extraBottomOffset = 20f
                            }
                        },
                        update = { chart ->
                            val entries = state.expenses.mapIndexed { index, data ->
                                Entry(index.toFloat(), data.amount.toFloat())
                            }

                            val dataSet = LineDataSet(entries, "消费金额").apply {
                                color = Color.BLUE
                                lineWidth = 2f
                                setDrawCircles(true)
                                setDrawValues(true) // 显示数值
                                valueTextSize = 10f
                                valueFormatter = object : ValueFormatter() {
                                    override fun getFormattedValue(value: Float): String {
                                        return "¥${value.toInt()}"
                                    }
                                }
                                circleRadius = 4f
                                setCircleColor(Color.BLUE)
                            }

                            chart.data = LineData(dataSet)
                            chart.invalidate()
                        }
                    )
                }
                is ExpenseChartState.Error -> {
                    Text(
                        text = state.message,
                        color = androidx.compose.ui.graphics.Color.Red,
                        modifier = Modifier.padding(vertical = 8.dp)
                    )
                }
            }
        }
    }
}